package com.walala.dispatcher.executor;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import com.alibaba.fastjson.JSON;
import com.walala.dispatcher.annotion.ExecutorHandler;
import com.walala.dispatcher.global.Constant;
import com.walala.dispatcher.global.RequestType;
import com.walala.dispatcher.pojo.RequestMsg;
import com.walala.dispatcher.redis.RedisClient;

/**
 * 拉取逻辑层
 */
@ExecutorHandler(requestType = RequestType.PULLOUT_LOGIC)
public class LogicPulloutExecutor extends DispatcherExecutor{
	
	private Logger logger = LoggerFactory.getLogger(LogicPulloutExecutor.class);
	
	public LogicPulloutExecutor(){
		this.type = RequestType.PULLOUT_LOGIC;;
	}
	
	public void dispatcher(ChannelHandlerContext ctx, DatagramPacket packet,RequestMsg requestMsg) {
		
		int requestType = requestMsg.getRequestType();
		if(requestType != RequestType.PULLOUT_LOGIC){
			logger.error("拉取logic请求非法，正确类型为：[{}],非法请求类型为:[{}]",RequestType.PULLOUT_LOGIC,requestType);
			return;
		}
		
		try {
			Jedis cluster = RedisClient.intance.getCluster();
			Map<String, String> map = cluster.hgetAll(Constant.LOGIC_SERVER_INFO);
			if (map != null) {
				String rspJson = JSON.toJSONString(map);
	            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(rspJson, CharsetUtil.UTF_8), packet.sender()));
	            logger.info("拉取logic成功,请求服务类型:{},服务器列表:{}", requestType, rspJson);
			}
		} catch (Exception e) {
			logger.error("拉取logic失败");
		}
		
	}

}
